package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.RetentPayConfigUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.RetentPayConfig;
import org.jsbd.boss.service.IChannelApkInfoService;
import org.jsbd.boss.service.IRetentPayConfigService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/retent/pay")
public class RetentPayConfigController {

	private static final Logger logger = LoggerFactory.getLogger(RetentPayConfigController.class);

	@Autowired
	private IRetentPayConfigService retentPayConfigService;
	@Resource
	private IChannelApkInfoService channelApkInfoService;
	@Resource
	private RedisClient redisClient;

	/**
	 * 配置列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list() {
		return "retentPay/list";
	}

	/**
	 * 配置数据
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/listJson", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> listJson(DataGridModel page, RetentPayConfig retentPayConfig) {
		String mark = retentPayConfig.getMark();
		if (StringUtils.isNotBlank(mark)) {
			String[] marks = mark.split(" ");
			List<String> keywords = new ArrayList<>();
			for (String keyword : marks) {
				keywords.add(keyword);
			}
			retentPayConfig.setKeywords(keywords);
		}
		
		return channelApkInfoService.selectAllRetentMarkInfo(page, retentPayConfig);
	}

	/**
	 * 配置次数
	 */
	@RequestMapping(value = "/configNum", method = RequestMethod.POST)
	@ResponseBody
	public void configNum(String marks, String date, Integer num, HttpServletResponse response) {
		String[] mark_arr = marks.split(",");
		List<RetentPayConfig> list = new ArrayList<RetentPayConfig>();
		try {
			for (int i = 0; i < mark_arr.length; i++) {
				RetentPayConfig retentPayConfig = new RetentPayConfig();
				retentPayConfig.setMark(mark_arr[i]);
				retentPayConfig.setDate(date);
				retentPayConfig.setNum(num);
				list.add(retentPayConfig);

				List<Integer> days = RetentPayConfigUtils.getDays(num);
				int[] arr_random = RetentPayConfigUtils.random(num);
				Map<Integer, Integer> map = new HashMap<Integer, Integer>();
				for (int j = 0; j < days.size(); j++) {
					map.put(days.get(j), arr_random[j]);
				}
				redisClient.hset(CacheKey.RETENT_PAY_CONFIG, mark_arr[i] + "-" + date, map);
			}
			retentPayConfigService.add(list);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	/**
	 * 是否支付
	 */
	@RequestMapping(value = "/isPay")
	@ResponseBody
	public Map<String, Object> isPay(String mark, HttpServletResponse response) {
		synchronized (this) {
			Map<String, Object> result = new HashMap<String, Object>();

			String month = DateUtil.getY_MStr();
			Integer curDay = RetentPayConfigUtils.getDayOfMonth(new Date());

			Map<Integer, Integer> map = (Map<Integer, Integer>) redisClient.hget(CacheKey.RETENT_PAY_CONFIG, mark + "-" + month);
			if (null == map || map.size() == 0) {
				result.put("resultCode", "1");
				result.put("resultMsg", false);
			} else {
				Integer payNum = map.get(curDay);
				// 当前日期之前未做的次数
				Integer beforPayNum = getBeforePayNum(curDay, map);
				
				if (null == payNum || payNum <= 0) {
					result.put("resultCode", "1");
					result.put("resultMsg", false);
				} else {
					payNum = payNum + beforPayNum;
					map.put(curDay, --payNum);
					redisClient.hset(CacheKey.RETENT_PAY_CONFIG, mark + "-" + month, map);
					result.put("resultCode", "1");
					result.put("resultMsg", true);
				}
			}
			return result;
		}
	}

	private Integer getBeforePayNum(Integer curDay, Map<Integer, Integer> map) {
		Integer num = 0;
		for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
			Integer key = entry.getKey();
			Integer value =  entry.getValue();
			if (key < curDay) {
				num += value;
				map.put(key, 0);
			}
		}
		return num;
	}
	
}
